# coding: utf-8
from utils import AbstractFunction
from PyQt5 import QtCore, QtGui, QtWidgets
from ui_design.config import Ui_Form
from functools import partial
import config
import os


class ConfigDialog(QtWidgets.QDialog, Ui_Form, AbstractFunction):
    def __init__(self, image_goal: str = '', image_base: str = '', parent=None):
        super(ConfigDialog, self).__init__(parent, flags=QtCore.Qt.WindowCloseButtonHint)
        self.setupUi(self)
        self.data_goal = ''
        self.data_base = ''

        self.edit_goal.textChanged.connect(partial(self.handle_user_edit, 'goal'))
        self.edit_base.textChanged.connect(partial(self.handle_user_edit, 'base'))

        self.setWindowTitle('配置项目')
        self.setMinimumSize(600, 480)
        self.edit_goal.setText(image_goal)
        self.edit_base.setText(image_base)

        self.edit_base.setReadOnly(True)
        self.edit_goal.setReadOnly(True)

        self.btn_goal.clicked.connect(self.handle_user_choose_goal_image)
        self.btn_base.clicked.connect(self.handle_user_choose_image_base)
        self.btn_cancel.clicked.connect(self.reject)
        self.btn_confirm.clicked.connect(self.do_confirm)

    def handle_user_edit(self, name, value):
        self.__dict__[f'data_{name}'] = value
        if name == 'goal' and value and os.path.exists(value):
            self.viewer.display_pix(QtGui.QPixmap(value))

    def handle_user_choose_goal_image(self):
        ld = self.get_last_directory()
        fp, _ = QtWidgets.QFileDialog.getOpenFileName(
            parent=self,
            caption='选取目标图片',
            directory=ld,
            filter=f'图片文件(*.{" *.".join(config.allowed_extensions)})'
            )
        if not fp:
            return
        fp = os.path.abspath(fp)
        self.save_last_directory(dir_path=os.path.dirname(fp))
        self.edit_goal.setText(fp)

    def handle_user_choose_image_base(self):
        ld = self.get_last_directory()
        fp, _ = QtWidgets.QFileDialog.getOpenFileName(
            parent=self,
            caption='选择图片库',
            directory=ld,
            filter=f'图片文件(*.{" *.".join(config.allowed_extensions)})'
            )
        if not fp:
            return
        fp = os.path.abspath(fp)
        self.save_last_directory(dir_path=os.path.dirname(fp))
        self.edit_base.setText(os.path.dirname(fp))

    def do_confirm(self):
        ls = []
        if not self.data_goal:
            ls.append('目标图片未选取')
        if not self.data_base:
            ls.append('图片库路径未选取')
        if ls:
            return self.show_warning_message(message=f'请注意以下问题:<br><ul><li>{"</li><li>".join(ls)}</li></ul>', parent=self, only_yes=True)

        self.accept()



if __name__ == '__main__':
    print(f'图片文件(*.{" *.".join(config.allowed_extensions)})')
    app = QtWidgets.QApplication([])
    c = ConfigDialog()
    c.show()
    app.exec_()